Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Python Functions → builtin and user defined

Python Functions

builtin and user defined

Functions are fundamental building blocks in Python, acting as reusable blocks of code that perform specific tasks. They enhance code readability, organization, and efficiency by avoiding repetition. Python offers two main categories of functions: built-in functions and user-defined functions.

1. Built-in Functions

These are pre-defined functions readily available in Python without needing any extra imports. They provide core functionalities for various operations. Let's explore some examples: `print()`: Displays output to the console. `len()`: Returns the length (number of items) of an object (string, list, tuple, etc.). `type()`: Returns the data type of an object. `input()`: Takes user input from the console.
Built-in function example print("Hello, world!") print(10 + 5) my_string = "Python" string_length = len(my_string) print(f"The length of '{my_string}' is: {string_length}") my_list = [1, 2, 3, 4, 5] list_length = len(my_list) print(f"The length of the list is: {list_length}") print(type(10)) print(type("hello")) print(type([1, 2, 3])) user_name = input("Enter your name: ") print(f"Hello, {user_name}!")

Output

Hello, world! 15 The length of 'Python' is: 6 The length of the list is: 5 <class 'int'> <class 'str'> <class 'list'> Enter your name: Sathish Hello, Sathish!
These are just a few examples; Python offers a rich library of built-in functions covering diverse functionalities (mathematical operations, string manipulation, file handling, etc.). You can find a comprehensive list in the official Python documentation.

2. User-Defined Functions

These are functions created by the programmer to encapsulate specific logic or operations needed within a program. They improve code modularity and reusability.

Structure of a user-defined function

Structure def function_name(parameter1, parameter2, ...): """Docstring: Describes what the function does.""" # Function body: Code to perform the task # ... return value # Optional return statement

Example 1: Simple function to add two numbers

python function to add two numbers def add_numbers(x, y): """This function adds two numbers and returns the sum.""" sum = x + y return sum result = add_numbers(5, 3) print(f"The sum is: {result}")

Output

The sum is: 8

Example 2: Function with default argument

Function with default argument def greet(name, greeting="Hello"): """Greets a person with a customizable greeting.""" print(f"{greeting}, {name}!") greet("Alice") greet("Bob", "Hi")

Output

Hello, Alice! Hi, Bob!


Tutorials